<?php
namespace app\common\service;

use think\facade\Db;

class Coupon extends Base {
    static $AUTH_CHECK = true; //默认必须登录
    //我的优惠券
    public function mycoupon(){
        $pagenum = input('post.pagenum');
        if(!$pagenum) $pagenum = 1;
        $pernum = 10;
        $st = input('param.st') ? input('param.st') : 0;
        $where = [];
        $where[] = ['user_id','=',$this->user_id];
        if($st == 0){//未使用
            $where[] = ['status','=',0];
            $where[] = ['endtime','>=',time()];
        }elseif($st == 1){
            $where[] = ['status','=',1];
        }elseif($st == 2){
            $where[] = ['status','=',0];
            $where[] = ['endtime','<',time()];
        }
        if(input('?param.sid') && input('param.sid')!==''){
            $where[] = ['sid','=',input('param.sid')];
        }
        $datalist = Db::name('coupon_record')->field('id,sid,type,limit_count,used_count,couponid,couponname,money,discount,minprice,from_unixtime(starttime,"%Y-%m-%d %H:%i") starttime,from_unixtime(endtime,"%Y-%m-%d %H:%i") endtime,from_unixtime(usetime) usetime,from_unixtime(createtime) createtime,status,from_mid')->where($where)->order('id desc')->page($pagenum,$pernum)->select()->toArray();
        if(!$datalist) $datalist = [];
        foreach($datalist as $k=>$v){
            $datalist[$k]['type_txt'] = logic('Coupon')->getCouponTypeTxt($v['type']);
            if($v['sid'] > 0){
                $binfo = Db::name('suppliers')->where('id',$v['sid'])->find();
                $datalist[$k]['sname'] = $binfo['name'];
            }
            $coupon = Db::name('coupon')->where('id',$v['couponid'])->field('isgive,fwtype')->find();
            //转赠优惠券不可二次转赠
            if($v['from_mid']){
                $datalist[$k]['isgive'] = 0;//不可二次转赠
            }else{
                $datalist[$k]['isgive'] = $coupon['isgive'];
            }
            $datalist[$k]['fwtype'] = $coupon['fwtype'];
        }
        $givecheckbox = false;
        return ['status'=>1,'data'=>$datalist,'givecheckbox'=>$givecheckbox];
    }

    //优惠券列表
    public function couponlist(){
        $pagenum = input('post.pagenum');
        if(!$pagenum) $pagenum = 1;
        $pernum = 20;

        $where2 = "find_in_set('-1',showtj)";
        if($this->user){
            $where2 .= " or find_in_set('".$this->user['level1']."',showtj)";
        }

        if(input('?param.sid') && input('param.sid')!==''){
            $sid = input('param.sid');
            $datalist= Db::name('coupon')->where(" tolist=1 and ($where2) and starttime<='".date('Y-m-d H:i:s')."' and endtime>='".date('Y-m-d H:i:s')."'")->where('sid',$sid)->order('sort desc,id desc')->page($pagenum,$pernum)->select()->toArray();
        }else{
            $datalist= Db::name('coupon')->where(" tolist=1 and ($where2) and starttime<='".date('Y-m-d H:i:s')."' and endtime>='".date('Y-m-d H:i:s')."'")->order('sort desc,id desc')->page($pagenum,$pernum)->select()->toArray();
        }
        if(!$datalist) $datalist = [];
        foreach($datalist as $k=>$v){
            $haveget = Db::name('coupon_record')->where('user_id',$this->user_id)->where('couponid',$v['id'])->count();
            $datalist[$k]['haveget'] = $haveget;
            $datalist[$k]['starttime'] = date('m-d H:i',strtotime($v['starttime']));
            $datalist[$k]['endtime'] = date('m-d H:i',strtotime($v['endtime']));
            $datalist[$k]['type_txt'] = logic('coupon')->getCouponTypeTxt($v['type']);
            if($v['yxqtype'] == 1){
                $yxqtime = explode(' ~ ',$v['yxqtime']);
                $datalist[$k]['yxqdate'] = date('Y-m-d',strtotime($yxqtime[1]));
            }elseif($v['yxqtype'] == 2){
                //领取后x天有效
                $datalist[$k]['yxqdate'] = date('Y-m-d',time() + 86400 * $v['yxqdate']);
            }elseif($v['yxqtype'] == 3){
                //次日起计算有效期
                $datalist[$k]['yxqdate'] = date('Y-m-d',strtotime(date('Y-m-d')) + 86400 * ($v['yxqdate'] + 1) - 1);
            }
            if($v['sid'] > 0){
                $binfo = Db::name('suppliers')->where('id',$v['sid'])->find();
                $datalist[$k]['sname'] = $binfo['name'];
            }

        }
        return ['status'=>1,'data'=>$datalist];
    }
    //领取优惠券
    public function getcoupon(){
        $this->checklogin();
        $post = input('post.');
        $coupon = Db::name('coupon')->where('id',$post['id'])->find();
        if(!$coupon) return $this->json(['status'=>0,'msg'=>t('优惠券').'已下架']);
        if(strtotime($coupon['starttime']) > time()) return $this->json(['status'=>0,'msg'=>'领取活动还没开始']);
        if(strtotime($coupon['endtime']) < time()) return $this->json(['status'=>0,'msg'=>'领取活动已结束']);
        if($coupon['stock']<=0) return $this->json(['status'=>0,'msg'=>'已抢光了']);
        $haveget = Db::name('coupon_record')->where('user_id',$this->user_id)->where('couponid',$post['id'])->count();
        if($haveget >= $coupon['perlimit']) return $this->json(['status'=>0,'msg'=>'您已领取过了']);


        $gettj = explode(',',$coupon['gettj']);
        if(!in_array('-1',$gettj) && !in_array($this->user['rank'],$gettj)){ //不是所有人
            return $this->json(['status'=>0,'msg'=>'您没有领取权限']);
        }
        if($coupon['price'] > 0){
            return $this->json(['status'=>0,'msg'=>'需要购买']);
        }
        if($coupon['score'] > 0){
            $user_wallet = Db::name('wallet')->where('user_id',$this->user_id)->find();
            if($user_wallet['score'] < $coupon['score']){
                return $this->json(['status'=>0,'msg'=>t('积分').'不足']);
            }
            qianbao($this->user_id,-$coupon['score'],'score','兑换优惠券',$desc='',$periods_id=0,$money_type=0);
        }
        $rs =  logic('coupon')->send($this->user_id,$coupon['id']);
        if(!$rs['status']){
            return $this->json(['status'=>0,'msg'=>$rs['msg']]);
        }
        return $this->json(['status'=>1,'msg'=>'领取成功','haveget'=>$haveget+1,'url'=>true]);
    }
    //优惠券详情
    public function coupondetail(){
        $rid = input('param.rid/d');
        if($rid){
            //如开启赠送，未登录也可查看
            $record = Db::name('coupon_record')->where('id',$rid)->find();
            $coupon = Db::name('coupon')->where('id',$record['couponid'])->find();
            $record['createtime'] = date('Y-m-d H:i:s',$record['createtime']);
            $record['usetime'] = date('Y-m-d H:i:s',$record['usetime']);
            $record['starttime'] = date('Y-m-d H:i:s',$record['starttime']);
            $record['endtime'] = date('Y-m-d H:i:s',$record['endtime']);
        }else{
            $id = input('param.id/d');
            if(!$id){
                return $this->json(['status'=>0,'msg'=>'参数错误']);
            }
            $coupon = Db::name('coupon')->where('id',$id)->find();
            if(empty($coupon)){
                return $this->json(['status'=>0,'msg'=>'该优惠券不存在']);
            }
            $record = [];
            $canget = true;
            if(strtotime($coupon['starttime']) > time()){
                $canget = false;
            }
            if(strtotime($coupon['endtime']) < time()){
                $canget = false;
            }
            if($coupon['stock']<=0){
                $canget = false;
            }
            $haveget = Db::name('coupon_record')->where('user_id',$this->user_id)->where('couponid',$coupon['id'])->count();
            if($haveget >= $coupon['perlimit']){
                $canget = false;
            }
            $coupon['canget'] = $canget;
        }
        $coupon['pack_coupon_list']=[];

        if($coupon['sid']!=0) $coupon['sname'] = Db::name('suppliers')->where('id',$coupon['sid'])->value('name');
        $rdata = [];
        $record['surplus_count'] = 0; //剩余次数
        if($coupon['limit_count'] !== '' && $record['used_count'] !== ''){
            $record['surplus_count'] = $coupon['limit_count']-$record['used_count'];
        }
        $rdata['record'] = $record;
        $rdata['coupon'] = $coupon;
        return $rdata;
    }

}
